package org.ccay.security.authc;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.ccay.security.entity.Permission;
import org.ccay.security.entity.Program;
import org.ccay.security.entity.Role;

public class DefaultProgramAuthorizationInfo implements
		ProgramAuthorizationInfo {
	
	private static final long serialVersionUID = 1L;
	
	
	protected Map<Program, LinkedHashSet<Role>> programRoles; 
	
    
	protected Set<Permission> permissions;
	
	/** 
	 * 遍历所有范围，获取角色集合
	 */
	@Override
	public Collection<String> getRoles() {
		Set<String> roles = new HashSet<String>();
		for(Map.Entry<Program, LinkedHashSet<Role>> entry : programRoles.entrySet()){
			for(Role r : entry.getValue()){
				roles.add(r.getName());
			}
		}
		return roles;
	}
	

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("DefaultProgramAuthorizationInfo [programRoles=");
		builder.append(programRoles);
		builder.append(", permissions=");
		builder.append(permissions);
		builder.append("]");
		return builder.toString();
	}

	

	@Override
	public Collection<Role> getObjectRoles() {
		Set<Role> roles = new HashSet<Role>();
		for(Map.Entry<Program, LinkedHashSet<Role>> entry : programRoles.entrySet()){
			roles.addAll(entry.getValue());
		}
		return roles;
	}

	@Override
	public Collection<Long> getRoleIds() {
		Set<Long> roles = new HashSet<Long>();
		for(Map.Entry<Program, LinkedHashSet<Role>> entry : programRoles.entrySet()){
			for(Role r : entry.getValue()){
				roles.add(r.getId());
			}
		}
		return roles;
	}
	
	@Override
	public Collection<String> getStringPermissions() {
		Set<String> result = new HashSet<String>();
		for(Permission p : permissions){
			result.add(p.getPermissionString());
		}
		return result;
	}
	
	@Override
	public Collection<Long> getProgramIds() {
		Set<Long> ids = new HashSet<Long>();
		for(Program p : programRoles.keySet()){
			ids.add(p.getProgramId());
		}
		return ids;
	}
	
	@Override
	public Collection<org.apache.shiro.authz.Permission> getObjectPermissions() {
		Set<org.apache.shiro.authz.Permission> result = new HashSet<org.apache.shiro.authz.Permission>();
		for(Permission p: permissions){
			result.add(p);
		}
		return result;
	}

	public void setStringPermissions(Set<String> stringPermissions) {
		permissions.clear();
		for(String p : stringPermissions){
			permissions.add(new Permission(p));
		}
	}

	public void setObjectPermissions(Set<Permission> permissions) {
		this.permissions = permissions;
	}

	@Override
	public Map<Program, LinkedHashSet<Role>> getProgramRoles() {
		return programRoles;
	}

	public void setProgramRoles(Map<Program, LinkedHashSet<Role>> programRoles) {
		this.programRoles = programRoles;
	}
}
